package com.example.asset.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.asset.common.Constants;
import com.example.asset.common.Result;
import com.example.asset.entity.AssetInformation;
import com.example.asset.entity.AssetLend;
import com.example.asset.entity.SysUser;
import com.example.asset.service.AssetInformationService;
import com.example.asset.service.AssetLendService;
import com.example.asset.utils.UtilToken;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.List;

@Tag(name = "资产借出管理")
@RestController
@RequestMapping("/lend")
public class AssetLendController{
    @Autowired
    private AssetLendService assetLendService;

    @Autowired
    private AssetInformationService assetInformationService;

    /**
     * 用于资产审核借出的翻页
     *
     * @param pageNum
     * @param pageSize
     * @param assetNumber (defaultValue="")
     * @return
     */
    @Operation(summary = "审核情况-用于资产审核借出的翻页")
    @GetMapping("/outpage")
    public Result outPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String assetNumber){
        IPage<AssetLend> page = new Page<>(pageNum, pageSize);
        QueryWrapper<AssetLend> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("audit", "否");
        queryWrapper.like("asset_number", assetNumber);
        IPage<AssetLend> assetInformationIPage = assetLendService.page(page, queryWrapper);
        return Result.success(assetInformationIPage);
    }


    /**
     * 用于资产借出的翻页
     *
     * @param pageNum
     * @param pageSize
     * @param assetNumber (defaultValue="")
     * @return
     */
    @Operation(summary = "资产借出-用于资产借出的翻页")
    @GetMapping("/ablelend")
    public Result AbleLendPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String assetNumber){
        IPage<AssetInformation> page = new Page<>(pageNum, pageSize);
        QueryWrapper<AssetInformation> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("asset_state", "正常");
        queryWrapper.like("asset_number", assetNumber);
        IPage<AssetInformation> assetInformationIPage = assetInformationService.page(page, queryWrapper);
        return Result.success(assetInformationIPage);
    }

    /**
     * 用于资产还入的翻页
     *
     * @param pageNum
     * @param pageSize
     * @param assetNumber (defaultValue="")
     * @return
     */
    @Operation(summary = "资产还入-用于资产还入的翻页")
    @GetMapping("/inpage")
    public Result inPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String assetNumber){
        IPage<AssetInformation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AssetInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssetInformation::getAssetState, "借出");
        queryWrapper.like(AssetInformation::getAssetNumber, assetNumber);
        if(!UtilToken.isAdmin()){
            SysUser currentUser = UtilToken.getCurrentUser();
            queryWrapper.eq(AssetInformation::getUeser, currentUser.getLoginName());
        }
        IPage<AssetInformation> assetInformationIPage = assetInformationService.page(page, queryWrapper);
        return Result.success(assetInformationIPage);
    }


    /**
     * 用于保存借出资产信息
     *
     * @param assetLend
     * @return
     */
    @Operation(summary = "资产借出-用于保存借出资产信息")
    @PostMapping
    public Result save(@RequestBody AssetLend assetLend){
        return Result.success(assetLendService.saveAssetLend(assetLend));
    }


    /**
     * 用于审核是否借出
     *
     * @param assetLend
     * @return
     */
    @Operation(summary = "资产借出-用于审核是否借出")
    @PostMapping("/audit")
    public Result judgeAudit(@RequestBody AssetLend assetLend){
        if(assetLend.getAudit().equals("是") && assetLend.getLendSerialnumber() != null){
            boolean flag1 = assetLendService.auditLend(assetLend);
            boolean flag2 = false;
            AssetLend lend = assetLendService.QuerryLendSerialNum(assetLend.getLendSerialnumber());
            if(lend != null){
                lend.setAudit("是");
                flag2 = assetLendService.saveOrUpdate(lend);
            }
            return Result.success(flag1 && flag2);
        } else{
            return Result.error(Constants.CODE_400, "参数错误");
        }
    }


    /**
     * 用于资产还入。更改资产状态为“正常”
     *
     * @param assetLend
     * @return
     */
    @Operation(summary = "资产还入-更改资产状态为正常")
    @PostMapping("/updatestate")
    public Result updateState(@RequestBody AssetLend assetLend){
        return Result.success(assetInformationService.UpdateAssetState(assetLend.getAssetNumber(), "正常"));
    }


    /**
     * 资产借出-导出借出信息
     *
     * @param response
     * @throws Exception
     */
    @Operation(summary = "资产借出-导出借出信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        // 从数据库查询出所有的数据
        List<AssetLend> list = assetLendService.list();

        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("资产借出", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
}